package cn.wolfcode.mq.linstener;

import cn.wolfcode.mq.MQConstant;
import cn.wolfcode.mq.OrderMQResult;
import cn.wolfcode.mq.OrderMessage;
import cn.wolfcode.service.IOrderInfoService;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

/**
 * @Author: 普发忠
 * @Date: 2021/11/11/14:17
 */
@Component
@RocketMQMessageListener(
        topic = MQConstant.ORDER_PEDDING_TOPIC,
        consumerGroup = "order_pedding_topic-consumer"
)
public class OrderPeddingListener implements RocketMQListener<OrderMessage> {
    @Autowired
    private IOrderInfoService orderInfoService;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;
    
    @Override
    public void onMessage(OrderMessage orderMessage) {
        OrderMQResult ret=new OrderMQResult();
        ret.setTime(orderMessage.getTime());
        ret.setSeckillId(orderMessage.getSeckillId());
        ret.setToken(orderMessage.getToken());
        String tag=MQConstant.ORDER_RESULT_SUCCESS_TAG;
    try {
        //尝试调用服务
        String orderNo=orderInfoService.order(orderMessage);
        ret.setOrderNo(orderNo);
        //成功发送延迟消息
        rocketMQTemplate.syncSend(MQConstant.ORDER_PAY_TIMEOUT_TOPIC, MessageBuilder.withPayload(ret).build(),
                5000,MQConstant.ORDER_PAY_TIMEOUT_DELAY_LEVEL);
    }catch (Exception e) {
        ret.setMsg("秒杀失败");
        ret.setCode(-101);
        e.printStackTrace();
//发送失败:fall
        tag=MQConstant.ORDER_RESULT_FAIL_TAG;
    }finally {
    //发送结果
       rocketMQTemplate.syncSend(MQConstant.ORDER_RESULT_TOPIC+":"+tag,ret);
    
    }
    }
}
